<?php

# Includo file di configurazione generale
require_once("inc/config.inc.php");

# Includo file di funzioni comuni
require_once("inc/common.inc.php");

# Inizializzo PostgreSQL
postgresql_connect();

# Includo Sessioni PostgreSQL
require_once("inc/postgresql_session.class.php");

# Includo Dijkstra
require_once("inc/dijkstra.php");

/* --- FUNZIONE PATH SELECTION --- */
function path_selection($id_progetto,$s,$d){
	global $DB;
	/* --- RECUPERO FILE CACHE --- */
	$cache = file("inc/postgis_graph.data");
	$row_max['max'] = trim($cache[0]);
	$offset = trim($cache[1]);
	$ourMap = unserialize(trim($cache[2]));
	
    $source = $s + $offset;
    $destination = $d + $offset;

    /* --- CALCOLO SHORTEST PATH --- */
    //Inizializzazione oggetto della classe Dijkstra
    $dijkstra = new Dijkstra($ourMap, 10000,count($ourMap));

    //Calcolo e restituzione dello Shortest Path
    $dijkstra->findShortestPath($source,$destination);
    $path = $dijkstra -> getResults($destination);

    //Sostituzione di ID con coordinate
    foreach($path as $node){
        if($node > $row_max['max']){
            $new_node = $node - $offset;
            $result_coord = pg_query($DB['link'], "SELECT x(coordinate) AS x, y(coordinate) AS y FROM OPERE WHERE id_opera = ".$new_node);
            $row_coord = pg_fetch_assoc($result_coord);
            $polyline[] = array($row_coord['x'],$row_coord['y']);
        }else{
            $result_coord = pg_query($DB['link'], "SELECT x(coordinate) AS x, y(coordinate) AS y FROM LINKS WHERE id_door = ".$node);
            $row_coord = pg_fetch_assoc($result_coord);
            $polyline[] = array($row_coord['x'],$row_coord['y']);
        }
    }

    //Restituzione delle coordinate della spezzata
    echo '<pre>';
    print_r($polyline);
    echo '</pre>';
    //return $polyline;
}

path_selection(127, 37, 39);
?>
